package controllers

import (
	"github.com/astaxie/beego"
	"shuxianghui/models"
	"HTshuxianghui/htmodels"
	"strconv"
	"time"
	"strings"
	"github.com/astaxie/beego/validation"
	"fmt"
)

type UsersController struct {
	beego.Controller
}

//带了参数导致bootstrap table无法正常使用
func (c *UsersController)HTUsersList_html() {
	str_UserType := c.Ctx.Input.URL()[strings.LastIndex(c.Ctx.Input.URL(), "/") + 1:]
	UserType, _ := strconv.Atoi(str_UserType)
	c.Data["UserType"] = UserType
	c.TplName = "users_list.html"
	c.Render()
}

func (c *UsersController)HTUsersList() {
	UserType, _ := c.GetInt("UserType")
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	fileds := []string{"Id", "Username", "UserType", "Email", "Phone"}
	Users := []models.Users{}
	htmodels.HTUsersGetList(&Users, fileds, UserType, offset, limit, search, "Phone", orderby)
	count, _ := htmodels.HTUsersGetCount(search, "Username", UserType, )
	c.Data["json"] = map[string]interface{}{"rows":&Users, "total":count}
	c.ServeJSON()
}

func (c *UsersController)HTUsersDetail() {
	Id, _ := c.GetInt64("Id")
	if Id != 0 {
		c.Data["update"] = true
		SetUsersDetailInfo(c, Id)
	}
	mytype, _ := c.GetInt("type")
	c.Data["Type"] = mytype
	c.TplName = "users_detail.html"
}

func SetUsersDetailInfo(c *UsersController, Id int64) {
	Users := models.Users{Id:int(Id)}
	htmodels.HTUsersGetDetail(&Users)
	if Users.CityId != 0 {
		c.Data["Dushuhui"] = htmodels.HTCityGetName(Users.CityId)
	}
	c.Data["Users"] = &Users
}

func (c *UsersController)HTUsersBasicDetail() {
	Id, _ := c.GetInt64("Id")
	if Id != 0 {
		c.Data["update"] = true
		SetUsersDetailInfo(c, Id)
	} else {
		Users := models.Users{Id:int(Id)}
		Users.Username = "超级管理员"
		Users.UserType = -1
		c.Data["Users"] = &Users
	}
	mytype, _ := c.GetInt("type")
	c.Data["Type"] = mytype
	c.TplName = "users_info.html"
}

func (c *UsersController)HTUsersAdd() {
	Users := models.Users{}
	if err := c.ParseForm(&Users); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("createtime")); err != nil {
		Users.CreateTime = time.Now()
	} else {
		Users.CreateTime = time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("updatetime")); err != nil {
		Users.UpdateTime = time.Now()
	} else {
		Users.UpdateTime = time_up
	}
	Users.Password = GetPassword("123456")

	valide := validation.Validation{}
	if b, err := valide.Valid(&Users); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTUsersAdd(&Users); err != nil {
		Message(&c.Controller, "", "添加失败，即将返回！" + err.Error(), "", true)
	}
	Message(&c.Controller, `/users/detail`, "添加成功！", "", false)
}

func (c *UsersController)HTUsersUpdate() {
	Id, _ := c.GetInt64("Id");
	Users := models.Users{Id:int(Id)}
	if err := htmodels.HTUsersGetDetail(&Users); err != nil {
		Message(&c.Controller, "", "严重错误，请联系管理员,即将返回！" + err.Error(), "", true)
	}
	if err := c.ParseForm(&Users); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("createtime")); err != nil {
		Users.CreateTime = time.Now()
	} else {
		Users.CreateTime = time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("updatetime")); err != nil {
		Users.UpdateTime = time.Now()
	} else {
		Users.UpdateTime = time_up
	}

	valide := validation.Validation{}
	if b, err := valide.Valid(&Users); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTUsersUpdate(&Users); err != nil {
		Message(&c.Controller, "", "更新失败，即将返回！" + err.Error(), "", true)
	}
	Message(&c.Controller, `/users/list_html` + `/` + strconv.Itoa(Users.UserType), "更新成功！", "", false)
}

func (c *UsersController)HTUsersDelete() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	count, err := htmodels.HTUsersDelete(Ids)
	if err != nil {
		Json_Message(&c.Controller, 0, "删除失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "删除" + strconv.FormatInt(count, 10) + "行")
}

func (c *UsersController)UsersGetMsm() {
	phone := c.GetString("Phone")
	valide := validation.Validation{}
	if v := valide.Phone(phone, "phone"); !v.Ok {
		Json_Message(&c.Controller, 0, "手机格式不对")
	}
	if code, _ := GetCache(phone); code != "" {
		phone_time, _ := GetCache(phone + "_time")
		if phone_time == "" {
			if err := Sendsms(phone, code); err != nil {
				fmt.Println(err)
				Json_Message(&c.Controller, 0, "短信重新发送失败")
			}
			PutIntoCache(phone + "_time", time.Now().Format("2006-01-02 15:04:05"), time.Second * 30)
			Json_Message(&c.Controller, 1, "重新发送成功")
		} else {
			Json_Message(&c.Controller, 0, "发送间隔太短")
		}
	}
	code := RandNum(6)
	if err := Sendsms(phone, code); err != nil {
		fmt.Println(err)
		Json_Message(&c.Controller, 0, "短信发送失败")
	}
	PutIntoCache(phone, code, time.Minute * 30)
	PutIntoCache(phone + "_time", time.Now().Format("2006-01-02 15:04:05"), time.Second * 30)
	Json_Message(&c.Controller, 1, "发送成功")
}

func (c *UsersController)UserRegist() {
	Users := models.Users{}
	if err := c.ParseForm(&Users); err != nil {
		Json_Message(&c.Controller, 0, "数据解析出现问题，请联系联系管理员")
	}
	if Users.CityId == 0 {
		provinceName := strings.Split(Users.CityName, " ")[0]
		err, norow, cityid := htmodels.HTCityGetProvince(provinceName + "-虚拟读书会")
		if norow {
			//插入读书会
			cityid = InsertDushuhui(c, provinceName + "-虚拟读书会", provinceName)
		} else if err != nil || cityid == 0 {
			Json_Message(&c.Controller, 0, "读书会表查询错误")
		} else {
			Users.CityId = cityid
		}
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("createtime")); err != nil {
		Users.CreateTime = time.Now()
	} else {
		Users.CreateTime = time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("updatetime")); err != nil {
		Users.UpdateTime = time.Now()
	} else {
		Users.UpdateTime = time_up
	}
	if err := htmodels.HTUserGetUserByPhone(&Users); err == nil {
		Json_Message(&c.Controller, 0, "此号已经被注册！")
	}
	Users.UserType = 1
	Users.Mark = 0
	Users.Rank = 0

	valide := validation.Validation{}
	if v := valide.MinSize(Users.Password, 6, "密码"); !v.Ok {
		Json_Message(&c.Controller, 0, "密码最少6位")
	}
	if v := valide.MaxSize(Users.Password, 30, "密码"); !v.Ok {
		Json_Message(&c.Controller, 0, "密码最多30位")
	}
	if v := valide.Required(Users.Username, "用户名"); !v.Ok {
		Json_Message(&c.Controller, 0, "用户名不可为空")
	}
	if v := valide.Phone(Users.Phone, "手机号"); !v.Ok {
		Json_Message(&c.Controller, 0, "手机号格式不正确")
	}

	Users.Password = GetPassword(c.GetString("Password"))
	//valide phone code
	code := c.GetString("code")
	if storedcode, _ := GetCache(Users.Phone); code != storedcode {
		Json_Message(&c.Controller, 0, "验证码错误")
	}

	if err := htmodels.HTUsersAdd(&Users); err != nil {
		Json_Message(&c.Controller, 0, "注册失败，即将返回！" + err.Error())
	}
	if err := htmodels.AddMarkOfCaculate(&Users, htmodels.RegitstMark); err != nil {
		fmt.Printf("add mark error when regitst for user:%d", Users.Id)
	}
	htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:"初始注册积分", LogTime:time.Now(), LogType:htmodels.LogType_MarkInit, Status:0})
	Json_Message(&c.Controller, 1, "注册成功")
}

func InsertDushuhui(c *UsersController, dushuhuiName string, province string) int {
	City := models.City{CityName:dushuhuiName, Virtural:1, CityPosition:province, CityOriginName:province}
	if err := htmodels.HTCityAdd(&City); err != nil {
		Message(&c.Controller, "", "创建读书会失败，即将返回！" + err.Error(), "", true)
	}
	dushuhui := models.Article{ArticleType:3, CityId:City.Id, CreateTime:time.Now(), EditTime:time.Now(), Content:"这里是" + City.CityName + "简介", Introduction:"这里是" + City.CityName + "简介"}
	if err := htmodels.HTArticleAdd(&dushuhui); err != nil {
		Message(&c.Controller, "", "添加地区成功，添加读书会简介失败，即将返回！" + err.Error(), "", true)
	}
	return City.Id
}

func (c *UsersController)UserLogin() {
	username := c.GetString("Phone")
	pass := c.GetString("Password")
	if username != "" {
		user := models.Users{Phone:username}
		emailOrPhone := false
		if strings.Index(username, "@") != -1 {
			emailOrPhone = true
		}
		if htmodels.HTCheckUserLogin(&user, username, GetPassword(pass), emailOrPhone) {
			Json_Message(&c.Controller, 1, "登录成功")
		} else {
			Json_Message(&c.Controller, 0, "用户名密码错误")
		}
	}
	Json_Message(&c.Controller, 0, "用户名密码不可为空")
}

func (c *UsersController)ResetPass() {
	username := c.GetString("Phone")
	pass := c.GetString("Password")
	valide := validation.Validation{}
	valide.MinSize(pass, 6, "password")
	valide.MaxSize(pass, 20, "password")
	if valide.HasErrors() {
		Json_Message(&c.Controller, 0, "密码要求6位到20位之间")
	}
	code := c.GetString("code")
	if code == "" {
		Json_Message(&c.Controller, 0, "验证码不可为空")
	}
	if storedcode, _ := GetCache(username); code != storedcode {
		Json_Message(&c.Controller, 0, "验证码错误")
	}
	if err := htmodels.UpdatePassword(GetPassword(pass), username); err != nil {
		Json_Message(&c.Controller, 0, "更新失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "密码修改成功")
}



//2017-09-20
func (c *UsersController)AddMarkHtml() {
	c.TplName = "AddScore.html"
}

func (c *UsersController)AddMark() {
	mark, _ := c.GetInt("mark")
	reason := c.GetString("reason")
	phone := c.GetString("phone")
	IsAdd := c.GetString("add")
	if mark <= 0 || reason == "" || IsAdd == "" || phone == "" {
		Json_Message(&c.Controller, 0, "参数不正确！")
	}
	user := models.Users{Phone:phone}
	if err := htmodels.HTUserGetUserByPhone(&user); err != nil {
		Json_Message(&c.Controller, 0, "用户不存在")
	}
	add := true
	if IsAdd == "0" {
		add = false
	}
	if err := htmodels.AddMark(&user, mark, add); err != nil {
		Json_Message(&c.Controller, 0, "操作错误" + err.Error())
	}
	if IsAdd == "0" {
		mark = -mark
	}
	htmodels.InsertLog(&models.SQLLogs{Mark:mark, UserId:user.Id, UserName:c.GetSession("name").(string), Body:reason, LogTime:time.Now(), LogType:htmodels.LogType_MarkOfAdmin, Status:0})
	Json_Message(&c.Controller, 1, "操作成功")
}


//2017-10-08
type UserWithDushuhui struct {
	User     *models.Users
	Dushuhui []models.City
}

func (c *UsersController)AddAdminPermissionHTML() {
	UserType := 100
	limit := 1000
	offset := int64(0)
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := ""
	fileds := []string{"Id", "Username", "UserType", "Email", "Phone"}
	Users := []models.Users{}
	if err := htmodels.HTUsersGetList(&Users, fileds, UserType, offset, limit, search, "Username", orderby); err != nil {
		fmt.Println(err)
		return
	}
	var userlist []UserWithDushuhui = make([]UserWithDushuhui, len(Users))
	for i := 0; i < len(Users); i++ {
		userlist[i].User = &Users[i]
		if err := htmodels.HTCityGetAdminCitiesByUserId(&userlist[i].Dushuhui, Users[i].Id); err != nil {
			fmt.Println(err)
			return
		}
	}

	//set current permission info
	currentUserId, _ := c.GetInt("UserId")
	var currentUnMatchedList []models.City
	var currentMatchedList []models.City
	if currentUserId == 0 {
		c.Data["disable"] = false
	} else {
		c.Data["disable"] = true
		CurrentUser := models.Users{Id:currentUserId}
		if err := htmodels.HTUsersGetDetail(&CurrentUser); err != nil {
			fmt.Println("get user wrong" + err.Error())
			return
		}
		if err := htmodels.HTCityGetAdminCitiesByUserId(&currentMatchedList, currentUserId); err != nil {
			fmt.Println(err)
			return
		}
		c.Data["phone"] = CurrentUser.Phone
		c.Data["name"] = CurrentUser.Username
	}
	if err := htmodels.HTCityGetAdminCitiesByUserId(&currentUnMatchedList, 0); err != nil {
		fmt.Println(err)
		return
	}

	c.Data["userlist"] = &userlist
	c.Data["matched"] = currentMatchedList
	c.Data["unmatched"] = currentUnMatchedList

	c.TplName = "addPermissions.html"
}

func (c *UsersController)UpdatePermission() {
	phone := c.GetString("phone")
	user := models.Users{Phone:phone}
	if err := htmodels.HTUserGetUserByPhone(&user); err != nil || user.UserType < 100 {
		Json_Message(&c.Controller, 1, "用户不存在或者用户不是分权管理员")
	}
	CityIds := make([]int, 0, 100)
	c.Ctx.Input.Bind(&CityIds, "CityIds")
	var checkmap map[int]bool = make(map[int]bool)

	var previousMatchedList []models.City
	if err := htmodels.HTCityGetAdminCitiesByUserId(&previousMatchedList, user.Id); err != nil {
		Json_Message(&c.Controller, 1, "查询错误" + err.Error())
	}
	fmt.Println(CityIds)
	if len(CityIds) > 0 {
		if err := htmodels.HTCityChangeAdminCitiesByUserId(CityIds, user.Id); err != nil {
			Json_Message(&c.Controller, 1, "修改用户权限错误" + err.Error())
		}
	}

	for _, v := range previousMatchedList {
		checkmap[v.Id] = true
	}
	for _, v := range CityIds {
		delete(checkmap, v)
	}
	var abandonList []int
	for k, v := range checkmap {
		if v {
			abandonList = append(abandonList, k)
		}
	}
	if len(abandonList) > 0 {
		htmodels.HTCityChangeAdminCitiesByUserId(abandonList, 0)
	}

	Json_Message(&c.Controller, 0, "修改成功")
}